from types import FunctionType

import localizing
from ui import print, input, endPassage

class Choice:
    """
    游戏的选项。
    """
    def __init__(self, name:str, func:FunctionType,localize_id:str = None) -> None:
        """
        没有设置localize_id的话默认为name。
        func 在选择了这个选项后执行，不传参。
        """
        if not localize_id: localize_id = name
        r = localizing.Localizer.I.get(localize_id)
        
        self.name = name
        self.text = r
        self.func = func

    def print(self, n:int) -> None:
        print("["+n+"]",self.text)

    def choose(self) -> None:
        self.func()

class ChoiceManager:
    """
    注册多个选项并一次性发出供用户选择。
    """
    def __init__(self) -> None:
        self.choices = []
    
    def addChoice(self,choice:Choice) -> "ChoiceManager":
        self.choices.append(choice)
        return self
    
    def Run(self) -> None:
        cs = self.choices
        self.choices = []
        for index, choice in enumerate( cs ):
            choice.print(str( index ))

        endPassage()

        while True:
            result = input( localizing.Localizer.I.get("textdungeon.choice.input") + " " )

            try:
                num = int ( result )
                if num < 0: raise IndexError
                choice = cs[num]

            except (ValueError, IndexError):
                print( localizing.Localizer.I.get("textdungeon.choice.invalid") )
                continue

            choice.choose()
            break

        endPassage()
            
